package com.atguigu.gmall.order.service.impl;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.HttpClientUtil;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.mapper.OrderDetailMapper;
import com.atguigu.gmall.order.mapper.OrderInfoMapper;
import com.atguigu.gmall.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 订单管理
 */
@Service
public class OrderInfoServiceImpl implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Value("${ware.url}")
    private String wareUrl;

    @Autowired
    private RabbitService rabbitService;

    //保存订单
    @Override
    public Long saveOrderInfo(OrderInfo orderInfo) {
        //1:订单表   返回值 订单ID  外健
        //订单状态
        orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
        //交易号
        String outTradeNo = "ATGUIGU" + System.currentTimeMillis() + new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);
        //生成订单时间
        orderInfo.setCreateTime(new Date());
        //过期时间  当前时间 追加 1天  明天
        Calendar calendar =  Calendar.getInstance();
        calendar.add(Calendar.DATE,10);
        Date time = calendar.getTime();
        orderInfo.setExpireTime(time);
        //进度
        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());
        //计算订单的总金额
        orderInfo.sumTotalAmount();

        //订单描述  将商品清单里的所有商品名称 进行拼接  之间用空格格开
        StringBuilder tradeBody = new StringBuilder();
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //拼接订单描述
        orderDetailList.forEach(orderDetail -> {
            tradeBody.append(orderDetail.getSkuName() + " ");
        });
        //订单描述
        orderInfo.setTradeBody(tradeBody.toString());
        //保存订单
        orderInfoMapper.insert(orderInfo);
        //2:订单详情表  商品清单
        orderDetailList.forEach(orderDetail -> {
            //外键
            orderDetail.setOrderId(orderInfo.getId());
            orderDetailMapper.insert(orderDetail);
        });

        //2小时以后取消订单  保存订单之后定时2小时后取消订单
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_DIRECT_ORDER_CANCEL,
                MqConst.ROUTING_ORDER_CANCEL, orderInfo.getId().toString(),MqConst.DELAY_TIME);
        return orderInfo.getId();
    }

    //验证库存
    @Override
    public boolean hasStock(Long skuId, Integer skuNum) {
       //远程调用库存管理系统
        String result = HttpClientUtil.doGet(wareUrl + "/hasStock?skuId=" + skuId + "&num=" + skuNum);
        return "1".equals(result);
    }

    //取消订单
    @Override
    public void cancelOrder(String orderId) {
        //1：判断查询一下订单是个什么状态
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        //2:未支付情况下才可以取消订单
        if(OrderStatus.UNPAID.name().equals(orderInfo.getOrderStatus())){
            //未支付
            orderInfo.setOrderStatus(OrderStatus.CLOSED.name());
            //进度状态
            orderInfo.setProcessStatus(ProcessStatus.CLOSED.name());
            //更新订单状态
            orderInfoMapper.updateById(orderInfo);

        }
    }
    //根据订单Id查询订单信息
    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        return orderInfoMapper.selectById(orderId);
    }

    //支付成功之后更新订单状态
    @Override
    public void updateOrderStatus(String orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(Long.parseLong(orderId));
        //未支付的情况下才会更新订单状态
        if(OrderStatus.UNPAID.name().equals(orderInfo.getOrderStatus())){
            //支付成功
            orderInfo.setOrderStatus(OrderStatus.PAID.name());
            //进度状态
            orderInfo.setProcessStatus(ProcessStatus.PAID.name());
            //
            orderInfoMapper.updateById(orderInfo);
        }

    }
}
